//
//  ViewModel.swift
//  LoadBSBJ
//
//  Created by eport_user1 on 2018/1/8.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

import UIKit
import Alamofire


typealias CloseType = (_ state:Bool,_ maxtime:String,_ array:[ContentModel]) -> Void


fileprivate var paramsDic = [String:String]()


class ViewModel: NSObject {

   class func loadData(a:String,type:Int,page:Int = 1,maxString:String = "",finshedBlock:@escaping(CloseType)) -> Void {
        
        var para = [String:String]()
        para["a"] = a
        para["c"] = "data"
        para["page"] = "\(page)"
        para["type"] = "\(type)"
        para["maxtimer"] = maxString
        
        paramsDic = para
        
        let url = URL.init(string: "http://api.budejie.com/api/api_open.php")
        
        Alamofire.request(url!, method: .get, parameters: paramsDic).responseJSON { (respond) in
           
            if paramsDic != para{
                
                return
            }
            
            switch(respond.result){
                
            case let .success(value):
                
                guard let dict = value as? [String:Any] else{
                    return
                }
                
                //datas判断是不是包含[string:any]类型数组
                guard let datas = dict["list"] as? [[String:Any]] else{
                    
                    return
                }
                
                var mmTime:String = ""
                
                
                if let lastTime = dict["info"] as? [String:Any] {
                    
                    mmTime = (lastTime["maxtime"] as? String) ?? ""
                    
                }
                
                var modelsArray = [ContentModel]()
                
                for dicx in datas{
                    
                    
                    let model = ContentModel.init(dict: dicx)
                    
                    modelsArray.append(model)
                    
                }
                
                finshedBlock(true,mmTime,modelsArray)
                
                
            case let .failure(error):
                
                
                finshedBlock(false,"",[ContentModel]())
                
                print(error)
                
            }
            
            
        }
        
        
        
    }
    
    
}
